#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2020/8/24 15:56
# @Author  : Mr. Cui
# @File    : views.py
# @Software: PyCharm
# index蓝图的视图

import json

from celery import Celery
from flask import request, make_response

from application.libs.framework import *
from . import ci
from .service import task, JobTask
from .service.jenkins_api import Job_yapi, task_sub_remind_new, ding_send, jenkins_ui
from ...apps.async_task.tasks import *
from ...apps.ci.service.client_api import *
from ...libs import const
from ...libs.validate_params import validate_params


@ci.route('/')
def index():
    task = JobTask.query.all()
    return str(task[0].task_name)


@ci.route('jenkins', methods=['GET'])
@validate_params(params=["job_name", "build_id"])
def jenkins():
    """
    jenkins调用的接口
    http://127.0.0.1:5000/ci/jenkins?job_name=shop-api-qa.360che.com&build_id=28
    :return:
    """
    JOB_NAME = request.args.get("job_name", "")
    BUILD_ID = request.args.get("build_id", "")
    count = 0
    while count < 3:  # 报错后，仅再执行两次
        count += 1
        try:
            case_type = Job_yapi.get_task_type(JOB_NAME)
            task_sub_remind_new(JOB_NAME, BUILD_ID)
            j_list = []
            if 1 in case_type:
                result_web_ui = jenkins_run_ui.delay(JOB_NAME, BUILD_ID, 1)
                j_list.append({"web_ui": result_web_ui.id})
            if 2 in case_type:
                result_app_ui = jenkins_run_ui.delay(JOB_NAME, BUILD_ID, 2)
                j_list.append({"app_ui": result_app_ui.id})
            if 3 in case_type:
                result_yapi = jenkins_run_yapi.delay(JOB_NAME, BUILD_ID, 3)
                j_list.append({"yapi": result_yapi.id})
            return jsonify(j_list)
        except Exception as e:
            ding_send(const.D_TOKEN, "qa-api--"+str(count)+"--jenkins异常，原因：%s" % e)
            time.sleep(3)
            db.session.rollback()
            continue


# todo 根据任务ID获取任务结果
@ci.route("/get_result/<result_id>")
def get_result(result_id):
    result = Celery.AsyncResult(id=result_id)
    return str(result.get())


# todo 根据任务ID获取任务状态
@ci.route("/get_status/<result_id>")
def get_status(result_id):
    result = Celery.AsyncResult(id=result_id)
    return result.status


# 测试
# @ci.route('jenkins_test')
# def jenkins_test():
#     JOB_NAME = 'shop-api-qa.360che.com'
#     BUILD_ID = '11'
#     case_type = Job_yapi.get_task_type(JOB_NAME)
#     j_list = []
#     if 1 in case_type:
#         result_web_ui = jenkins_run_ui.delay(JOB_NAME, BUILD_ID, 1)
#         j_list.append({"web_ui": result_web_ui.id})
#     if 2 in case_type:
#         jenkins_ui(JOB_NAME, BUILD_ID, 1)
#     if 3 in case_type:
#         result_yapi = jenkins_run_yapi.delay(JOB_NAME, BUILD_ID, 3)
#         j_list.append({"yapi": result_yapi.id})
#     return jsonify(j_list)


@ci.route('/search', methods=['POST'])
@validate_params(params=["page_num", "page_per"])
def sel_search_all():
    """
    条件搜索
    :return: json
    """
    task_list = task.get_search_list(request.json)
    return result(const.SUCCESS, None, task_list)


@ci.route('/task_list', methods=['POST'])
@validate_params(params=["create_time", "ding_token", "id", "job_name", "status", "task_name", "page_num", "page_per"])
def sel_all():
    """
    查询全部
    :return: json
    """
    task_list = task.get_task_list(request.json)
    return result(const.SUCCESS, None, task_list)


@ci.route('/add_task', methods=['POST'])
@validate_params(params=["task_name", "job_name", "ding_token"])
def add_task():
    """
    添加
    :return: json
    """
    taskname = request.form.get('task_name')
    jobname = request.form.get('job_name')
    dingtoken = request.form.get('ding_token')
    message = task.add_task(taskname, jobname, dingtoken)
    return result(const.SUCCESS, message, None)


@ci.route('/deltask/<id>', methods=['GET'])
def del_task(id):
    """
    删除
    :param id: id
    :return: json
    """
    message = task.del_task(id)
    return result(const.SUCCESS, message, None)


@ci.route('/begtask/<id>', methods=['GET'])
def beg_task(id):
    """
    启动项目
    :param id: id
    :return: json
    """
    message = task.begin_task(id)
    return result(const.SUCCESS, message, None)


@ci.route('/stoptask/<id>', methods=['GET'])
def stop_task(id):
    """
    停止项目
    :param id: id
    :return: json
    """
    message = task.stop_task(id)
    return result(const.SUCCESS, message, None)


@ci.route('/uptask_byid', methods=['POST'])
@validate_params(params=["id", "task_name", "job_name", "ding_token", "status"])
def uptask_byid():
    """
    修改任务
    :return: json
    """
    task_querys = request.json
    id = task_querys['id']
    task_name = task_querys['task_name']
    job_name = task_querys['job_name']
    ding_token = task_querys['ding_token']
    status = task_querys['status']
    message = task.upjobtask_byid(id, task_name, job_name, ding_token, status)
    return result(const.SUCCESS, message, None)


@ci.route('/sel_case', methods=['POST'])
@validate_params(params=["group", "project"])
def sel_case():
    """
    查询case
    :return: json
    """
    group = request.form.get('group')
    project = request.form.get('project')
    res = task.sel_case(group, project)
    return result(const.SUCCESS, None, res)


@ci.route('/addcase', methods=['GET', 'POST'])
@validate_params(params=["task_id", "case_id", "node_id"])
def add_case():
    """
    添加case
    :return: json
    """
    task_id = request.form.get('task_id')
    case_id = request.form.get('case_id')
    node_id = request.form.get('node_id')
    message = task.add_case(task_id, case_id, node_id)
    if message == const.INSERT_SUCCESS:
        message = task.add_case_deploy(case_id, node_id, task_id)  # 自动部署
        if message == const.OPERATE_SUCCESS:
            code = const.SUCCESS
        else:
            code = const.FAIL_40000
    else:
        code = const.FAIL_40000
    return result(code, message, None)


@ci.route('/sel_taskcase/<id>', methods=['GET'])
def sel_taskcase(id):
    """
    查询任务下的case
    :param id: id
    :return: json
    """
    res = task.sel_taskcase(id)
    return result(const.SUCCESS, None, res)


@ci.route('/dell_taskcase', methods=['POST'])
@validate_params(params=["task_id", "case_id"])
def dell_taskcase():
    """
    删除case
    :return: json
    """
    taskid = request.form.get('task_id')
    caseid = request.form.get('case_id')
    message = task.del_case(taskid, caseid)
    return result(const.SUCCESS, message, None)


@ci.route('/sub_report', methods=['POST'])
@validate_params(params=["task_id", "build_id", "case_id", "type", "total", "succ", "fail", "err", "info"])
def sub_report():
    """
    给自动化提交报告用
    :return:
    """
    try:
        data = json.loads(request.data)
        task_id = data["task_id"]
        build_id = data["build_id"]
        case_id = data["case_id"]
        type = data["type"]
        total = data["total"]
        succ = data["succ"]
        fail = data["fail"]
        err = data["err"]
        info = data["info"]
        ret = update_report_service(task_id, build_id, case_id, type, total, succ, fail, err, info)
        while True:
            if ret:
                return make_response("", 204)
            else:
                ret = update_report_service(task_id, build_id, case_id, type, total, succ, fail, err, info)
    except Exception as e:
        print(e)
        return make_response(result_msg(const.FAIL_400, "提交失败,参数有误，%s" % str(e)), const.FAIL_400)
